<template>
  <div class="panel history-images">
    <h2 class="panel-title">
      <Picture class="el-icon" />
      历史监控图片
    </h2>
    <div class="images-container">
      <div v-if="latestImages.length === 0" class="no-data">
        <el-icon><Picture /></el-icon>
        <span>暂无历史图片</span>
      </div>
      <div v-else v-for="(image, index) in latestImages" :key="image.id" class="image-card">
        <el-image 
          :src="image.photoUrl" 
          :alt="`监控图片 ${index + 1}`"
          fit="cover"
          :preview-src-list="previewUrls"
          @error="handleImageError"
        >
          <template #error>
            <div class="image-error">
              <el-icon><Picture /></el-icon>
              <span>加载失败</span>
            </div>
          </template>
          <template #placeholder>
            <div class="image-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
          </template>
        </el-image>
        <div class="image-info">
          <div class="time">{{ formatTime(image.createTime) }}</div>
          <div class="device">设备: {{ getDeviceName(image) }}</div>
        </div>
      </div>
    </div>
    <div v-if="loading" class="loading-mask">
      <el-icon class="loading-icon"><Loading /></el-icon>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { Picture, Loading } from '@element-plus/icons-vue'
import { cameraApi } from '@/api'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()
const latestImages = ref([])
const loading = ref(false)
const retryCount = ref(0)
const maxRetries = 3

// 检查token是否存在
const checkToken = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.error('请先登录')
    router.push('/login')
    return false
  }
  return true
}

// 计算预览图片列表
const previewUrls = computed(() => {
  return latestImages.value.map(img => img.photoUrl).filter(Boolean)
})

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '未知时间'
  const date = new Date(timestamp)
  return date.toLocaleString('zh', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取设备名称
const getDeviceName = (image) => {
  if (!image) return '未知设备'
  if (image.device?.sensorId) return image.device.sensorId
  if (image.device?.name) return image.device.name
  return 'AB9831171' // 默认设备号
}

// 处理图片加载错误
const handleImageError = (error) => {
  console.error('图片加载失败:', error)
  if (retryCount.value < maxRetries) {
    retryCount.value++
    setTimeout(() => {
      fetchLatestImages()
    }, 2000 * retryCount.value) // 递增重试延迟
  }
}

// 获取历史图片
const fetchLatestImages = async () => {
  if (loading.value || !checkToken()) return
  loading.value = true
  try {
    const response = await cameraApi.getHistoricalData()
    
    // 处理响应数据
    if (response && Array.isArray(response)) {
      latestImages.value = response
        .filter(item => (
          item && 
          item.photoUrl && 
          !item.isDeleted && 
          item.createTime
        ))
        .map(item => ({
          id: item.id,
          photoUrl: item.photoUrl,
          createTime: item.createTime,
          device: item.device
        }))
        .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        .slice(0, 4) // 显示最新的4张图片

      if (latestImages.value.length === 0) {
        ElMessage.warning('暂无历史图片')
      } else {
        retryCount.value = 0 // 重置重试计数
      }
    } else {
      throw new Error('返回数据格式错误')
    }
  } catch (error) {
    console.error('获取图片失败:', error)
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      router.push('/login')
      return
    }
    const errorMsg = error.response?.data || error.message || '获取历史图片失败，请稍后重试'
    ElMessage.error(errorMsg)
    
    // 如果是网络错误，尝试重试
    if (error.message.includes('network') && retryCount.value < maxRetries) {
      retryCount.value++
      setTimeout(() => {
        fetchLatestImages()
      }, 2000 * retryCount.value)
    } else {
      latestImages.value = []
    }
  } finally {
    loading.value = false
  }
}

// 定时刷新图片
let timer
const startAutoRefresh = () => {
  if (checkToken()) {
    fetchLatestImages()
    // 每5分钟刷新一次
    timer = setInterval(() => {
      if (checkToken()) {
        retryCount.value = 0 // 重置重试计数
        fetchLatestImages()
      }
    }, 5 * 60 * 1000)
  }
}

onMounted(() => {
  startAutoRefresh()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
</script>

<style scoped>
.history-images {
  height: calc(100% - 420px);
  position: relative;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 15px;
  height: calc(100% - 50px);
}

.no-data {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 14px;
  gap: 10px;
}

.no-data .el-icon {
  font-size: 32px;
}

.image-card {
  flex: 1;
  min-width: calc(50% - 8px);
  max-width: calc(50% - 8px);
  position: relative;
  border-radius: 4px;
  overflow: hidden;
  background: rgba(0, 0, 0, 0.2);
  aspect-ratio: 16/9;
}

.el-image {
  width: 100%;
  height: 100%;
}

.image-error,
.image-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #888;
  font-size: 14px;
  gap: 10px;
  background: rgba(0, 0, 0, 0.1);
}

.image-error .el-icon,
.image-loading .el-icon {
  font-size: 32px;
}

.image-loading .el-icon {
  animation: rotate 1s linear infinite;
}

.image-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: #fff;
  backdrop-filter: blur(5px);
}

.time {
  font-size: 12px;
  margin-bottom: 4px;
  color: #42b983;
}

.device {
  font-size: 14px;
  color: #fff;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.loading-icon {
  font-size: 32px;
  color: #42b983;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

:deep(.el-image__inner) {
  transition: transform 0.3s;
}

:deep(.el-image__inner:hover) {
  transform: scale(1.05);
}
</style> 